﻿var g_Condit;//查詢條件
var g_imgExp = "../Images/Exp.png";//Detl展開圖示
var g_imgCol = "../Images/Col.png";//Detl收和圖示
var g_BlockIMG = "../../images/loading.gif";//Grid Loading
var g_BlockBG = "#FFFACD"; //Grid Loading backgroundColor
var g_imgDesc = "../../Images/Desc.png";//
var g_imgAsc = "../../Images/Asc.png";//

//設定資料表的單雙行色系
var g_odd = "#fffbd6";
var g_even = "#ffffff";


function gdb_DataBind(p_Source, p_Method, p_PageIndex, p_PageSize, p_OrderBy, p_Condit, p_TargetDiv)
{
    try
    {
        $("#" + p_TargetDiv + "PageControl").attr("OrderBy", p_OrderBy);

        var m_ConditionKey = "";
        for (var Param in p_Condit)
        {
            m_ConditionKey += Param + ": '" + p_Condit[Param] + "',";
        }
        $("#" + p_TargetDiv + "PageControl").attr("Condit", m_ConditionKey);
        GridBlock(p_Source, p_Method, p_PageIndex, p_PageSize, p_OrderBy, p_TargetDiv);

    }
    catch (e)
    {
        alert(e.message);
    }
}
function GetEvent(e)
{
    return e.target ? e.target : $(event.srcElement || event.target).context;
}

var timer;
var firing = false;

//Add By Ben 20130603 Grid ondbclick觸發事件
function GridEventHandler_dbClick(e, p_TargetDiv)
{
    //擷取觸發控制項
    var obj = GetEvent(e);
    switch (obj.tagName)
    {
        case "TD":
            if ($("#" + obj.id).parent().length > 0)
            {
                var m_TrId = $("#" + obj.id).parent()[0].id;
                SelectedRow(p_TargetDiv, m_TrId);
                if ($("#" + p_TargetDiv).attr('ondbTarget') != undefined)
                {
                    $("#MainContent_" + $("#" + p_TargetDiv).attr('ondbTarget'))[0].click();
                }
            }
            break;
    }
}
//Add By Ben 20130603 Grid觸發事件
function GridEventHandler(e, p_TargetDiv)
{
    if (firing)
    {
        clearTimeout(timer);
        GridEventHandler_dbClick(e, p_TargetDiv);
        firing = false;
        return;
    }
    firing = true;
    timer = setTimeout(function ()
    {
        clearTimeout(timer);
        GridEventHandler_Click(e, p_TargetDiv)
        firing = false;
    }, 250);
}


//點選GridOnclick事件處理
function GridEventHandler_Click(e, p_TargetDiv,p_IsDouble)
{
    //擷取觸發控制項
    var obj = GetEvent(e);
    switch (obj.tagName)
    {
        case "IMG": //圖片
            if ($("#" + obj.id).attr("tp"))  //圖片排序
                gridBar_MouseOnClick(p_TargetDiv, obj.id.replace("img", ""));
            else //判斷是否點到+-圖 
                DetlCtrl(obj, p_TargetDiv)
            break;
        case "TH":
            gridBar_MouseOnClick(p_TargetDiv, obj.id.replace("th",""));
            break;
        case "LABEL":
            if ($("#" + obj.id).attr("tp"))
                gridBar_MouseOnClick(p_TargetDiv, obj.id.replace("lbl", ""));
            break;
        case "TD":
            if ($("#" + obj.id).parent().length>0)
            {
                var m_TrId = $("#" + obj.id).parent()[0].id;
                SelectedRow(p_TargetDiv,m_TrId);
            }
            break;
    }
}
function getPageIndex(p_PageIndex)
{
    var m_PageIndex = 1;
    if (p_PageIndex)
        m_PageIndex = p_PageIndex
return m_PageIndex
}



function SelectedRow(p_TargetDiv, p_TrId)
{
    $(".SelectedRow").removeClass("SelectedRow");
    //$("#" + p_TrId + " td").addClass("SelectedRow");
    $("." + p_TargetDiv + " #" + p_TrId + " td").addClass("SelectedRow");
    var m_Source = $("#" + p_TargetDiv + "PageControl").attr("Source");
    var m_ColumnsNames = $("#" + p_TargetDiv + "_Grid th");
    var m_Param = "";
    $("." + p_TargetDiv + " #" + p_TrId + " td").each(function (index)
    {
        m_Param += ((index == 0) ? "" : ",") + "" + m_ColumnsNames[index].id.replace("th", "") + ":'" + $.trim($(this).text()) + "'";
    });
    var m_ConditionKey = $("#" + p_TargetDiv + "PageControl").attr("Condit");
    
    m_ConditionKey += "PageIndex: '" + $("#" + p_TargetDiv + "PageControl").attr("PageIndex") + "',TrIndex:'" + p_TrId + "'";

    //2013/7/2 vicky--改為同步執行，因當double click太快時會錯誤
    $.ajax({
        type: "POST",
        async:false, 
        url: m_Source + ".aspx/SetGridKey",
        data: "{ p_Param : {" + m_Param + "},p_ConditionKey:{" + m_ConditionKey + "}}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error)
        {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data)
        {
        }
    });
}


function ExpDetl(p_RowIndex, p_TargetDiv)
{
    var p_Source = $("#" + p_TargetDiv + "PageControl").attr("Source");
    var p_Method = $("#" + p_TargetDiv + "PageControl").attr("Detl");
   
    $("#tr" + p_RowIndex + " td").each(function (index)
    {
        $.trim($(this).text())
    });
    var m_ColumnsNames = $("#" + p_TargetDiv + "_Grid th");
    var m_Where = "";
    //取得欄位名稱多國語言
   

    $("#tr"+p_RowIndex + " td").each(function( index ) {
        m_Where += ((index == 0) ? "" : ",") + "p_" + m_ColumnsNames[index].id.replace("th", "") + ":'" + $.trim($(this).text()) + "'";

    });
    $.ajax({
        type: "POST",
        url: p_Source + ".aspx/" + p_Method,
        data: "{" + m_Where + " }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error)
        {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data)
        {
            var DetlTbHtml = "<Table align='center' class='GridTableDetails' style='table-layout:fixed;width: 95%; border:1px solid #c6c6c6;'>";
            var m_JsonObj = data.d;
            var m_ColLan = "";

            $.each(m_JsonObj, function (RowCount, DataRow)
            {
                var ColumnConut = 0;
                var m_TRCount = 0;

                $.each(DataRow, function (ColumnName, Value)
                {
                    m_ColLan += ((ColumnConut != 0) ? "," : "") + "'" + ColumnName + "'";
                    ColumnConut++;
                });
                ColumnConut = 0;
                var m_RetrunObj = GetLanguage(m_ColLan);

                $.each(DataRow, function (ColumnName, Value)
                {
                    if (ColumnConut % 2 == 0)
                    {
                        DetlTbHtml += "<tr>"
                    }
                    DetlTbHtml += "<td class='DetlCol'>" + m_RetrunObj[ColumnName] + "</td><td class='DetlVal'>" + ((Value != null) ? Value : "") + "</td>";
                    if (ColumnConut % 2 == 1)
                    {
                        DetlTbHtml += "</tr>"
                        m_TRCount++;
                    }
                        ColumnConut++;
                });
                DetlTbHtml += "</Table>"
            });
            var HideColumnCount = $("#" + p_TargetDiv + "PageControl").attr("HideColumn").split(",");
            if (($("#" + p_TargetDiv + "PageControl").attr("HideColumn")==""))
                HideColumnCount=0;
            ($("#" + p_TargetDiv + "PageControl").attr("HideColumn").split(",").length)
            $("#tr" + p_RowIndex).after($("<tr class='ExpTR' id='ExpTR" + p_RowIndex + "'><td colspan='" + ((m_ColumnsNames.length) - HideColumnCount).toString() + "' style='width: 100%;'>" + DetlTbHtml + "</td></tr>"));
        }
    });
}
function DetlCtrl(obj, p_TargetDiv)
{
    //圖片位置
    
    //是否多筆展開
    var m_isMulti = false;
    //紀錄點選到的資料列
    var RowIndex = obj.id.replace("img", "");
    //紀錄點選+圖的位置
    var ExpIndex = $("#divGrid").attr("ExpIndex");
    if ($("#" + obj.id).attr("src").indexOf("Exp.png") != -1)
    {
        $("#divGrid").attr("ExpIndex", RowIndex);
        if (RowIndex != ExpIndex)
        {
            if (!m_isMulti)
            {
                if (ExpIndex)
                    $("#img" + ExpIndex).attr("src", g_imgExp);
                $("#ExpTR" + ExpIndex).remove();
            }
            $("#img" + RowIndex).attr("src", g_imgCol);
            ExpDetl(RowIndex, p_TargetDiv);
        }
        else
        {
            $("#img" + RowIndex).attr("src", g_imgCol);
            ExpDetl(RowIndex, p_TargetDiv);
        }
    }
    else
    {
        if (!m_isMulti)
        {
            $("#ExpTR" + ExpIndex).remove();
            $("#img" + ExpIndex).attr("src", g_imgExp);
        }
        else
        {
            $("#ExpTR" + RowIndex).remove();
            $("#img" + RowIndex).attr("src", g_imgExp);
        }
    }
}
function CheckReserved(p_ColumnsName)
{
    var m_isKeyWord = false;
    var m_ReservedWord = new Array('TOTRECORD', 'TOTPAGE');
    $.each(m_ReservedWord, function (index)
    {
        if (p_ColumnsName == m_ReservedWord[index])
            m_isKeyWord = true;
    });
    return m_isKeyWord;
}
function GridBlock(p_Source, p_Method, p_PageIndex, p_PageSize, p_OrderBy,  p_TargetDiv)
{
    $('div.' + p_TargetDiv).block({
        fadeIn: 700,
        fadeOut: 700,
        message: "<img src=\"" + g_BlockIMG + "\" /> ", css: {
            border: 'none',
            padding: '0px',
            opacity: .8
        },
        overlayCSS: { backgroundColor: g_BlockBG },
        onBlock: function ()
        {
            var WhereParam = $("#" + p_TargetDiv + "PageControl").attr("Condit");
            
            $.ajax({
                type: "POST",
                url: p_Source + ".aspx/" + p_Method,
                data: "{ " + WhereParam + "p_PageInfo : {OrderBy:'" + p_OrderBy + "',PageIndex:'" + p_PageIndex + "',PageSize:'" + p_PageSize + "',TargetDiv:'" + p_TargetDiv + "'}}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data)
                {
                    DataLoad(data.d, p_Source, p_Method, p_PageIndex, p_PageSize, p_OrderBy,  p_TargetDiv);
                }
            });

        }

    });
}


function getRootPath()
{
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}
function GetLanguage(p_ColLan)
{
    var Path = getRootPath() + "/Default.aspx";
    var m_RetrunObj = "";
    $.ajax({
        type: "POST",
        url: Path + "/GetLanguage",
        data: "{ ColLan : [" + p_ColLan + "]}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        error: function (xmlHttpRequest, error)
        {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data)
        {
            m_RetrunObj = data.d;
        }
    });
    return m_RetrunObj;
}


function TextAlignHandler(p_TargetDiv,p_ColumnsCount)
{
    var m_TextAlign = "text-align:center;";
    if ($("#" + p_TargetDiv + "PageControl").attr("textalign") != undefined)
    {
        var m_AlignColumns = $("#" + p_TargetDiv + "PageControl").attr("textalign").split(",");
        m_TextAlign = "text-align:";
        if (m_AlignColumns[p_ColumnsCount - 1] != undefined)
        {
            switch (m_AlignColumns[p_ColumnsCount - 1])
            {
                case "C": //置中
                    m_TextAlign += "center;";
                    break;

                case "R": //靠右
                    m_TextAlign += "right;";
                    break;
                case "L": //靠左
                    m_TextAlign += "left;";
                    break;
                default:
                    m_TextAlign += "center;";
                    break;
            }
        }
        else
            m_TextAlign = "text-align:center;";
    }
   
    return m_TextAlign;
}

function DataLoad(p_JSON, p_Source, p_Method, p_PageIndex, p_PageSize, p_OrderBy,  p_TargetDiv)
{


    var m_JsonObj = p_JSON;

    var m_html = " <div id='divGrid' >";
    m_html += "<table id='" + p_TargetDiv + "_Grid' class='GridTableHeader' style='width: 100%;'> ";
    m_html += "<tr >"
    var is_NoData = false;
    if (m_JsonObj[0].ReturnCode == undefined)
    {
        $("#" + p_TargetDiv + "PageControl").attr("Source", p_Source);
        $("#" + p_TargetDiv + "PageControl").attr("Method", p_Method);
        $("#" + p_TargetDiv + "PageControl").attr("PageSiz", p_PageSize);
        $("#" + p_TargetDiv + "PageControl").attr("OrderBy", p_OrderBy);
        $("#" + p_TargetDiv + "PageControl").attr("PageIndex", p_PageIndex);
        var m_With = $("#" + p_TargetDiv + "PageControl").attr("GridWidth").split(",");
        var m_RowCount = m_JsonObj[0].TOTRECORD;
        var m_TotPage = m_JsonObj[0].TOTPAGE;

        var m_Pages = m_JsonObj[0].TOTPAGE;
        $("#" + p_TargetDiv + "PageControl").attr("Pages", m_RowCount)
        var m_From = (parseInt(p_PageIndex) * parseInt(p_PageSize) - parseInt(p_PageSize) + 1).toString();
        var m_To = (parseInt(p_PageIndex) * parseInt(p_PageSize)).toString();

        var ColumnsCount = 1;
        $("#" + p_TargetDiv + "PageControl").attr("HideColumn", $("#" + p_TargetDiv + "PageControl").attr("HideColumn") + ",RNUM");
        var m_HideColumns = $("#" + p_TargetDiv + "PageControl").attr("HideColumn").split(",");

        //取得欄位名稱多國語言
        var m_ColLan = "";
        var m_ColCount = 0;
        for (var ColumnsName in m_JsonObj[0])
        {
            if (!CheckReserved(ColumnsName))
            {
                m_ColLan += ((m_ColCount != 0) ? "," : "") + "'" + ColumnsName + "'";
                m_ColCount++;
            }
           
        }
        var m_RetrunObj = GetLanguage(m_ColLan);
        for (var ColumnsName in m_JsonObj[0])
        {
            if (!CheckReserved(ColumnsName))
            {
                //判斷隱藏欄位====================
                var isVisibleColumn = "";
                $.each(m_HideColumns, function (Count, HideColumn)
                {
                    if (ColumnsName == HideColumn)
                        isVisibleColumn = "display:none";
                });
                //判斷隱藏欄位====================
                //文字對齊====================
                var m_TextAlign = TextAlignHandler(p_TargetDiv,ColumnsCount);
                //文字對齊====================
                ////測試
                //if (ColumnsCount == 1) {
                //    if ($("#" + p_TargetDiv + "PageControl").attr("showact") != "False") {
                //        m_html += "<th id='th_img style='font-weight:bold; width:10%; " + m_TextAlign + "; ><label tp='th' id=\"lbl_OPT \">功能</label></th>";
                //    }
                //}

                if (p_OrderBy != "")
                {
                    if (p_OrderBy.substr(0, p_OrderBy.indexOf(" ")) == ColumnsName)
                    {
                        var m_OrderImg = "";
                        if (p_OrderBy.substr(p_OrderBy.indexOf(" ") + 1) == "ASC")
                            m_OrderImg = "&nbsp;<img src='" + g_imgAsc + "' tp='ASC' Class='OrderBy' id='img" + ColumnsName + "'/>";
                        else
                            m_OrderImg = "&nbsp;<img src='" + g_imgDesc + "' tp='DESC' Class='OrderBy' id='img" + ColumnsName + "'/>";
                        m_html += "<th id='th" + ColumnsName + "' style='font-weight:bold; width:" + m_With[ColumnsCount - 1] + "; " + m_TextAlign + "; " + isVisibleColumn + " ' onmouseover='gridBar_MouseOver(event);'  onmouseout=\"gridBar_MouseOut(event);\"  > <label tp='th' id=\"lbl" + ColumnsName + "\">" + m_RetrunObj[ColumnsName] + "</label>" + m_OrderImg + "</th>";
                    }
                    else
                    {
                        m_html += "<th id='th" + ColumnsName + "' style='font-weight:bold; width:" + m_With[ColumnsCount - 1] + "; " + m_TextAlign + "; " + isVisibleColumn + " ' onmouseover='gridBar_MouseOver(event);'  onmouseout=\"gridBar_MouseOut(event);\"  ><label tp='th' id=\"lbl" + ColumnsName + "\">" + m_RetrunObj[ColumnsName] + "</label></th>";

                    }
                }
                else
                    m_html += "<th id='th" + ColumnsName + "' style='font-weight:bold; width:" + m_With[ColumnsCount - 1] + "; " + m_TextAlign + "; " + isVisibleColumn + " ' onmouseover='gridBar_MouseOver(event);'  onmouseout=\"gridBar_MouseOut(event);\"  ><label tp='th' id=\"lbl" + ColumnsName + "\">" + m_RetrunObj[ColumnsName] + "</label></th>";
                ColumnsCount++;
            }
        }
        
        m_html += " </table></div>";
        m_html += " <div class='scroll' id='boxscroll' style='height:92%;'>";
        m_html += " <table id='GridTable' class='' style='table-layout:fixed;width: 100%;'>";
        var TRClass = "";
        $.each(m_JsonObj, function (RowCount, DataRow)
        {
            m_html += "<tr id=tr" + RowCount + " " + TRClass + " >";
            var ColumnCount = 1;
            var m_Detl = "";
            $.each(DataRow, function (ColumnName, DataValue)
            {
                if (!CheckReserved(ColumnName))
                {
                    //判斷隱藏欄位====================
                    var isVisibleColumn = "";
                    $.each(m_HideColumns, function (Count, HideColumn)
                    {
                        if (ColumnName == HideColumn)
                        {
                            isVisibleColumn = "display:none";
                        }
                    });
                    //判斷隱藏欄位==================== 
                    if (ColumnCount == 1)
                    {
                        if ($("#" + p_TargetDiv + "PageControl").attr("Detl") != "False") {
                            m_Detl = "<img id='img" + RowCount + "'  src='" + g_imgExp + "'/>&nbsp;";
                        }
                        //if ($("#" + p_TargetDiv + "PageControl").attr("showact") != "False") {
                        //    m_IMG = "<input type='image' id='img_ACT_D" + RowCount + "' src='../../Images/Delete.gif' onclick='DeleteRow(event,this.id);' /> &nbsp;";
                        //    m_IMG = m_IMG + "<input type='image' id='img_ACT_U" + RowCount + "' src='../../Images/Edit.gif' onclick='EDditRow(event,this.id);' /> &nbsp;";
                        //    m_IMG = m_IMG + "<input type='image' id='img_ACT_Q" + RowCount + "' src='../../Images/Query.gif' onclick='ViewRow(event,this.id);' /> &nbsp;";
                            
                        //    m_html += "<td id='col_" + p_TargetDiv + RowCount.toString() + ColumnCount.toString() + "' style='width:10%; " + m_TextAlign + "; ' >" + m_IMG  + "</td>";
                        //}
                    }
                    else
                        m_Detl = "&nbsp;";

                    //文字對齊====================
                    var m_TextAlign = TextAlignHandler(p_TargetDiv, ColumnCount);
                    //文字對齊====================

                    m_html += "<td id='col_" + p_TargetDiv + RowCount.toString() + ColumnCount.toString() + "' style='width:" + m_With[ColumnCount - 1] + "; " + m_TextAlign + "; " + isVisibleColumn + "' >" + m_Detl + ((DataValue == null) ? "" : DataValue) + "</td>";
                    ColumnCount++;
                }

            });
            m_html += "</tr>";

        });

        if (m_RowCount != "")
        {

            $("#" + p_TargetDiv + "btnFirst").off('click');
            $("#" + p_TargetDiv + "btnFirst").on('click', function ()
            {
                BtnFirstOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });
            $("#" + p_TargetDiv + "btnPrev").off('click');
            $("#" + p_TargetDiv + "btnPrev").on('click', function ()
            {
                BtnPrevOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });
            $("#" + p_TargetDiv + "btnNext").off('click');
            $("#" + p_TargetDiv + "btnNext").on('click', function ()
            {
                BtnNextOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });

            $("#" + p_TargetDiv + "btnGoto").off('click');
            $("#" + p_TargetDiv + "btnGoto").on('click', function ()
            {
                BtnGotoOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });
            $("#" + p_TargetDiv + "btnLast").off('click');
            $("#" + p_TargetDiv + "btnLast").on('click', function ()
            {
                BtnLastOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });
           
            $("#" + p_TargetDiv + "drpPage").off('change');
            $("#" + p_TargetDiv + "drpPage").on('change', function ()
            {
                $("#" + p_TargetDiv + "PageIndex").val($("#" + p_TargetDiv + "drpPage").val());
                BtnGotoOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv);
            });


        }
      //  $("#" + p_TargetDiv + "PageInfo").html("<label id=\"lblTOTAL\">" + "搜尋結果 共" + "</label>&nbsp;" + m_RowCount + "&nbsp;<label id=\"lblRECORDS\">" + ("筆") + "</label>，" + "<label id=\"lblCURRENT_RECORD_IN\">" + ("目前位置") + "</label>&nbsp;" + m_From + "~" + m_To + "&nbsp;<label id=\"lblRECORDS\">" + ("，") + "</label>" + "頁次/總頁數：" + p_PageIndex.toString() + "/" + m_TotPage.toString());
        $("#" + p_TargetDiv + "PageIndex").maxLength = Math.ceil(m_RowCount / p_PageSize).toFixed(0).length;
        $("#" + p_TargetDiv + "PageControl").show();
        
        //$("#txtPage").html(m_TotPage.toString() + "頁");
        //$("#txtPageCount").html(m_RowCount.toString());
        //$("#divPageinfo").show();

        $("#" + p_TargetDiv + "txtPage").html(m_TotPage.toString() + "頁");
        $("#" + p_TargetDiv + "txtPageCount").html(m_RowCount.toString());
        $("#" + p_TargetDiv + "divPageinfo").show();
        
        AdddrpPage(p_TargetDiv, m_TotPage);

    }
    else
    {
        is_NoData = true;
        $("#" + p_TargetDiv + "PageControl").hide();
    }
    m_html += " </table>";

    $("#" + p_TargetDiv).html(m_html);

    //設定資料表的單雙行色系
    $("#GridTable tr:odd").css({ backgroundColor: g_odd });
    $("#GridTable tr:even").css({ backgroundColor: g_even });

    var nicesx = $("#boxscroll").niceScroll({ touchbehavior: false, cursorcolor: "#7A7A7A", cursoropacitymax: 0.9, cursorwidth: 13 });
    if ($("#" + p_TargetDiv + "PageControl").attr("ScrollPage") == "true")
    {
        $('#boxscroll').scroll(function ()
        {
            if (($("#GridTable").height() - $('#boxscroll').height() - 5) < $('#boxscroll').scrollTop())
            {
                Scroll_Data(p_PageSize, p_Source, p_Method, p_TargetDiv);
            }
        });
    }
    if (is_NoData)
    {
        if (m_JsonObj[0].ReturnCode == "100")
        {
            MsgBlock(p_TargetDiv, "查無資料!", false);
        }
        else
        {
            MsgBlock(p_TargetDiv, m_JsonObj[0].Message + "  " + m_JsonObj[0].LogMessage,true );
        }
    }
}

function AdddrpPage(p_TargetDiv, p_PageCount)
{
    $("#" + p_TargetDiv + "drpPage").empty();
    for (i = 1; i <= p_PageCount; i = i + 1)
    {
        var Sel = ""; 
        if ($("#" + p_TargetDiv + "PageControl").attr("PageIndex") == i.toString())
            Sel = "selected='selected'";
        $("#" + p_TargetDiv + "drpPage").append($("<option " + Sel + " ></option>")
                     .attr("value", i.toString())
                     .text(i.toString()));
    }
}
    

//Scroll Data
function Scroll_Data(p_PageSize, p_Source, p_Method, p_TargetDiv) {
    var m_PageIndex = $("#" + p_TargetDiv + "PageControl").attr("PageIndex");
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    if (parseInt(m_row_count) > parseInt(m_PageIndex) * parseInt(p_PageSize)) {
        m_PageIndex = (parseInt(m_PageIndex) + 1);
        $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

        $('div.' + p_TargetDiv).block({
            fadeIn: 700,
            fadeOut: 700,
            message: "<img src=\"" + g_BlockIMG + "\" /> ", css: {
                border: 'none',
                padding: '0px',
                opacity: .8
            },
            overlayCSS: { backgroundColor: g_BlockBG },
            onBlock: function () {
                var WhereParam = $("#" + p_TargetDiv + "PageControl").attr("Condit");

                $.ajax({
                    type: "POST",
                    url: p_Source + ".aspx/" + p_Method,
                    data: "{ " + WhereParam + "p_PageInfo : {OrderBy:'" + m_OrderBy + "',PageIndex:'" + m_PageIndex + "',PageSize:'" + p_PageSize + "',TargetDiv:'" + p_TargetDiv + "'}}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var TRClass = "";
                        var m_html = "";
                        var m_With = $("#" + p_TargetDiv + "PageControl").attr("GridWidth").split(",");
                        var m_HideColumns = $("#" + p_TargetDiv + "PageControl").attr("HideColumn").split(",");
                        m_JsonObj = data.d;
                        $.each(m_JsonObj, function (RowCount, DataRow) {
                         var m_TrCount=  (parseInt(m_PageIndex) - 1) * parseInt(p_PageSize) + RowCount;
                         m_html += "<tr id=tr" + m_TrCount + " " + TRClass + " >";
                            var ColumnCount = 1;
                            var m_Detl = "";
                            $.each(DataRow, function (ColumnName, DataValue) {
                                if (!CheckReserved(ColumnName)) {
                                    //判斷隱藏欄位====================
                                    var isVisibleColumn = "";
                                    $.each(m_HideColumns, function (Count, HideColumn) {
                                        if (ColumnName == HideColumn) {
                                            isVisibleColumn = "display:none";
                                        }
                                    });
                                    //判斷隱藏欄位==================== 
                                    if (ColumnCount == 1)
                                    {
                                        if ($("#" + p_TargetDiv + "PageControl").attr("Detl") != "False")
                                            m_Detl = "<img id='img" + m_TrCount + "'  src='" + g_imgExp + "'/>&nbsp;";
                                    }   
                                    else
                                        m_Detl = "&nbsp;";
                                    m_html += "<td id='col" + m_TrCount.toString() + ColumnCount.toString() + "' style='width:" + m_With[ColumnCount - 1] + "; " + isVisibleColumn + "' >" + m_Detl + ((DataValue == null) ? "" : DataValue) + "</td>";
                                    ColumnCount++;
                                }

                            });
                            m_html += "</tr>";

                        });
                        $("#GridTable").append(m_html);
                        $("#GridTable tr:odd").css({ backgroundColor: g_odd });
                        $("#GridTable tr:even").css({ backgroundColor: g_even });

                        $("div." + p_TargetDiv).unblock();
                    }
                });

            }

        });
    }

}

//第一頁
function BtnFirstOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv)
{
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    var m_LastPage = "";
    var m_PageIndex = "1";
    $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

    if ((m_row_count % parseInt(p_PageSize)) == 0)
        m_LastPage = parseInt(m_row_count / parseInt(p_PageSize)).toString();
    else
        m_LastPage = (parseInt(m_row_count / parseInt(p_PageSize)) + 1).toString();

    if (parseInt(m_LastPage) > parseInt(m_PageIndex))
    {
        GridBlock(p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy,  p_TargetDiv);

    }
}

//下一頁function BtnNextOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv)
{
    var m_PageIndex = $("#" + p_TargetDiv + "PageControl").attr("PageIndex");
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    if (parseInt(m_row_count) > parseInt(m_PageIndex) * parseInt(p_PageSize))
    {
        m_PageIndex = (parseInt(m_PageIndex) + 1);
        $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

        GridBlock(p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy, p_TargetDiv);

    }
}
//上一頁function BtnPrevOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv)
{
    var m_PageIndex = $("#" + p_TargetDiv + "PageControl").attr("PageIndex");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    if (m_PageIndex > 1)
    {
        m_PageIndex = (parseInt(m_PageIndex) - 1);
        $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

        GridBlock(p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy, p_TargetDiv);

    }
}
//最後頁
function BtnLastOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv)
{
    var m_PageIndex = $("#" + p_TargetDiv + "PageControl").attr("PageIndex");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    if ((m_row_count % parseInt(p_PageSize)) == 0)
    {
        m_PageIndex = parseInt(m_row_count / parseInt(p_PageSize)).toString();
    }
    else
    {
        m_PageIndex = (parseInt(m_row_count / parseInt(p_PageSize)) + 1).toString();
    }
    $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

    GridBlock(p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy, p_TargetDiv);

}
//GoTo
function BtnGotoOnclick(p_PageSize, p_Source, p_Method, p_TargetDiv)
{
    var m_row_count = $("#" + p_TargetDiv + "PageControl").attr("Pages");
    var m_OrderBy = $("#" + p_TargetDiv + "PageControl").attr("OrderBy");
    var m_LastPage = "";
    var m_PageIndex = $("#" + p_TargetDiv + "PageIndex").val();
    $("#" + p_TargetDiv + "PageControl").attr("PageIndex", m_PageIndex);

    if (m_PageIndex != "0")
    {
        if ((m_row_count % parseInt(p_PageSize)) == 0)
        {
            m_LastPage = parseInt(m_row_count / parseInt(p_PageSize)).toString();
        }
        else
        {
            m_LastPage = (parseInt(m_row_count / parseInt(p_PageSize)) + 1).toString();
        }
        if (parseInt(m_LastPage) >= parseInt(m_PageIndex))
        {
            GridBlock(p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy, p_TargetDiv);
        }
    }
}




function MsgBlock(p_TargetDiv, m_Msg, m_isError)
{
    $("div." + p_TargetDiv).block({
        message: m_Msg, css: {
            border: 'none',
            padding: '15px',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .6
        }
    });

    if (!m_isError)
    {
        setTimeout("unblockUI('" + p_TargetDiv + "')", 1000);
    }
}

function unblockUI(p_TargetDiv)
{
    $("div." + p_TargetDiv).unblock()
}
function gridBar_MouseOut(e) {
    e = GetEvent(e);
    if (e.tagName == "TH") {
        e.style.backgroundColor = "";
        e.style.fontWeight = "bold";
    }
}

function gridBar_MouseOver(e) {
    e = GetEvent(e);
    if (e.tagName == "TH") {
        e.style.fontWeight = "bold";
        e.style.cursor = "hand";
    }
}
function gridBar_MouseOnClick(p_TargetDiv, m_ColumnsName)
{
    var p_Source = $("#" + p_TargetDiv + "PageControl").attr("Source");
    var p_Method = $("#" + p_TargetDiv + "PageControl").attr("Method");
    var p_PageSize = $("#" + p_TargetDiv + "PageControl").attr("PageSiz");

    var m_PageIndex = "1";
    var m_OrderBy = "";
    if ($(".OrderBy").length == 0)
        m_OrderBy = m_ColumnsName + " DESC";
    else
    {
        if ($(".OrderBy").attr("tp") == "DESC")
            m_OrderBy = m_ColumnsName + " ASC";
        else
            m_OrderBy = m_ColumnsName + " DESC";
    }
    $("#" + p_TargetDiv + "PageControl").attr("OrderBy", m_OrderBy);

    var WhereParam = $("#" + p_TargetDiv + "PageControl").attr("Condit");
    
    $.ajax({
        type: "POST",
        url: p_Source + ".aspx/" + p_Method,
        data: "{ " + WhereParam + "p_PageInfo : {OrderBy:'" + m_OrderBy + "',PageIndex:'" + m_PageIndex + "',PageSize:'" + p_PageSize + "',TargetDiv:'" + p_TargetDiv + "'}}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            DataLoad(data.d, p_Source, p_Method, m_PageIndex, p_PageSize, m_OrderBy, p_TargetDiv);
        }
    });
}

